﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Management.Automation;
using System.Text;

namespace SPWebShell.cmdlet
{
    [Cmdlet(VerbsData.Update, "HttpFile" )]
    public class HttpPutFile : CmdLetBase
    {
        [Parameter(Mandatory = true, HelpMessage = "The absolute URL of the item on the web site where the file will be created or updated if an existing document is found . e.g. http://server/sites/SiteA/lists/Tasks/MyEditFormas.aspx")]
        [ValidateNotNullOrEmpty]
        public string Url { get; set; }

        [Parameter(Mandatory = false, HelpMessage = "The name/path of the file which will be uploaded to SharePoint")]
        [ValidateNotNullOrEmpty]
        public string File { get; set; }

        protected override void ProcessRecord()
        {
            try
            {
                WriteVerbose("Start time: " + DateTime.Now.ToString());
                WriteVerbose("Verifying for the presence of file:"+this.File);
                string filePath=System.IO.Path.GetFullPath(this.File);
                if (!System.IO.File.Exists(filePath))
                {
                    throw new Exception(string.Format("The file:{0} was not found",filePath));
                }
                WriteVerbose("File found");
                byte[] content = System.IO.File.ReadAllBytes(filePath);
                ISPRepository repos = base.SPRepos;
                WriteVerbose("Before calling method PutAnyDocument");
                Guid etag = repos.PutAnyDocument(content, this.Url);
                WriteVerbose("After calling method PutAnyDocument");
                WriteObject(etag);
                base.ProcessRecord();
            }
            catch (System.Web.Services.Protocols.SoapException ex)
            {
                string message = ex.Detail.OuterXml;
                throw new Exception(message, ex);
            }
            finally
            {
                WriteVerbose("End time: " + DateTime.Now.ToString());
            }
        }
    }
}
